import { getXPath } from '@/lib/utils';
import { PersistenMode, PersistentSettings, Status, useSettingsStore } from '@/store';

const href = location.href;

export const scopeStorageKey = 'PERSISTENT-SCOPE';
export const globalStorageKey = 'PERSISTENT-GLOBAL';

export interface GlobalData {
  [href: string]: string;
}

export interface ScopeData {
  [href: string]: {
    [xpath: string]: string;
  };
}

const store = {
  getItem<T>(key: string): T | null {
    const value = localStorage.getItem(key);
    if (value) {
      return JSON.parse(value);
    } else {
      return null;
    }
  },
  setItem<T>(key: string, value: T) {
    try {
      localStorage.setItem(key, JSON.stringify(value));
    } catch {
      alert('存储已经满了');
    }
  },
  removeItem(key: string) {
    localStorage.removeItem(key);
  },
};

function saveEditedInfo(event: Event, persistentSettings: PersistentSettings) {
  const target = event.target as HTMLElement;
  if (target) {
    if (persistentSettings.currentMode === PersistenMode.GlobalMode) {
      // 清理所有的 script 脚本,暂时不进行清理,如果清理了会导致依赖脚本的样式出现问题
      // const scripts = document.scripts;
      // // 需要注意 scripts 是动态的
      // const len = scripts.length;
      // for (let i = 0; i < len; i++) {
      //   const script = scripts[i];
      //   script.remove();
      // }
      store.setItem(globalStorageKey, {
        [href]: document.documentElement.innerHTML,
      });
    } else {
      const text = target.textContent;
      const path = getXPath(target);
      if (path) {
        const prevData = store.getItem<ScopeData>(scopeStorageKey);
        if (prevData && prevData[href]) {
          store.setItem(scopeStorageKey, {
            [href]: {
              ...prevData[href],
              [path]: text,
            },
          });
        } else {
          store.setItem(scopeStorageKey, {
            [href]: {
              [path]: text,
            },
          });
        }
      }
    }
  }
}

export function useSave() {
  const status = useSettingsStore((state) => state.status);
  const persistentSettings = useSettingsStore((state) => state.persistentSettings);
  useEffect(() => {
    if (status === Status.STOP) {
      return;
    }
    function hangdlerInput(event: Event) {
      saveEditedInfo(event, persistentSettings);
    }
    document.addEventListener('input', hangdlerInput);
    return () => {
      document.removeEventListener('input', hangdlerInput);
    };
  }, [status, persistentSettings]);
}

// 清理
function deleteAll() {
  store.removeItem(scopeStorageKey);
  store.removeItem(globalStorageKey);
}

function handlerMessage(message: string) {
  if (message === 'clear') {
    deleteAll();
  }
}

export function useDelete() {
  useEffect(() => {
    chrome.runtime.onMessage.addListener(handlerMessage);
    return () => {
      chrome.runtime.onMessage.removeListener(handlerMessage);
    };
  }, []);

  return {
    deleteAll,
  };
}
